package com.foreveredu.propms.web.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.foreveredu.propms.domain.District;
import com.foreveredu.propms.domain.House;
import com.foreveredu.propms.domain.SubDistrict;
import com.foreveredu.propms.domain.User;
import com.foreveredu.propms.domain.Utilities;
import com.foreveredu.propms.service.IBusinessService;
import com.foreveredu.propms.service.IChargeService;
import com.foreveredu.propms.service.IManagementService;
import com.foreveredu.propms.web.struts.actionform.UtilitiesActionForm;

/**
 * 执行物业收费操作
 * @author hushigang
 *
 */
public class UtilitiesAction extends AbstractBaseDispatchAction {

	private IChargeService chargeService = null;
	private IManagementService managementService = null;
	private IBusinessService businessService = null;
	
	//获得日志记录器
	private Logger log = Logger.getLogger(UtilitiesAction.class);
	
	public IChargeService getChargeService() {
		return chargeService;
	}
	
	public void setChargeService(IChargeService chargeService) {
		this.chargeService = chargeService;
	}

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	public IBusinessService getBusinessService() {
		return businessService;
	}

	public void setBusinessService(IBusinessService businessService) {
		this.businessService = businessService;
	}

	// 跳转水电报表上传页面
	public ActionForward upload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 获取当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal().getUsername());
		} catch(ClassCastException e) {
			//用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		
		// 获取当前物业管理员所在的物业服务处
		District dis = user.getDistrict();
		request.setAttribute("dis", dis);
		
		// 获取该物业管理处下的小区
		Set<SubDistrict> subs = dis.getSubs();
		List<SubDistrict> subList = new ArrayList<SubDistrict>();
		subList.addAll(subs);
		request.setAttribute("subList", subList);
		
		return mapping.findForward("upload");
	}
	
	// 完成水电报表上传操作
	@SuppressWarnings("unchecked")
	public ActionForward uploadSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 获取当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal().getUsername());
		} catch(ClassCastException ex) {
			//用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		
		// 获取当前物业管理员所在的物业服务处
		District dis = user.getDistrict();
		request.setAttribute("dis", dis);
		
		// 获取该物业管理处下的小区
		Set<SubDistrict> subs = dis.getSubs();
		List<SubDistrict> subList = new ArrayList<SubDistrict>();
		subList.addAll(subs);
		request.setAttribute("subList", subList);
		
		//获得表单数据
		UtilitiesActionForm uaf = (UtilitiesActionForm)form;
		
		//获得水电报表所对应的小区
		SubDistrict sub = managementService.findSubDistrictById(uaf.getSubId());
		
		//获得水电报表日期
		int chargeYear = uaf.getChargeYear();
		int chargeMonth = uaf.getChargeMonth();
		
		// 将水电报表上传到服务器的report文件夹中
		String dirPath = request.getSession().getServletContext().getRealPath("/report");

		// 判断路径是否存在，如果不存在，就创建这个路径
		File fileDir = new File(dirPath);
		if (!fileDir.exists()) {
			fileDir.mkdir();
		}

		Hashtable<Object, Object> files = form.getMultipartRequestHandler().getFileElements();

		String reportName = null;

		for (Enumeration<Object> e = files.keys(); e.hasMoreElements();) {
			String key = (String) e.nextElement();

			try {
				FormFile formFile = (FormFile) files.get(key);
				String fileName = formFile.getFileName().trim();// 获得待上传的文件名

				if (fileName == null || fileName.equals("")) {
					request.setAttribute("fileEmptyError", "上传的EXCEL文件为空！");
					
					return mapping.findForward("upload");
				}

				// 读出原文件的扩展名
				String ext = "";
				int pos = fileName.lastIndexOf(".");
				ext = fileName.substring(pos);// 得到扩展名

				if (!ext.equalsIgnoreCase(".xls")) {
					request.setAttribute("fileFormatError", "文件类型不对，只能是EXCEL类型！");
					
					return mapping.findForward("upload");
				}

				// 拼出完整的新文件名
				if(chargeMonth < 10) {
					reportName = sub.getId() + "_" + chargeYear + "0" + chargeMonth + ext;
				} else {
					reportName = sub.getId() + "_" + chargeYear + chargeMonth + ext;
				}
				
				//判断本小区本月度水电报表是否已经上传，重新上传，视为修改报表，则删除已有数据
				File theFile = new File(dirPath + File.separatorChar + reportName);
				if (theFile.exists()) {
					List<House> houseList = managementService.findHousesBySubId(sub);
					for(House house:houseList) {
						businessService.deleteUtilitiesByHouseAndDate(house,chargeYear,chargeMonth);
					}
				}
				
				InputStream is = formFile.getInputStream();
				OutputStream os = new FileOutputStream(dirPath + File.separatorChar + reportName);

				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = is.read(buffer)) != -1) {
					os.write(buffer, 0, bytesRead);
				}
				os.flush();

				is.close();
				os.close();

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		//上传水电报表完毕后，读取该报表中的数据，并写入到数据库中
		String path = dirPath + File.separatorChar + reportName;

		InputStream fis = null;
		Workbook workbook = null;
		try {
			fis = new FileInputStream(path);
			workbook = Workbook.getWorkbook(fis);//获得当前工作簿
			Sheet sheet = workbook.getSheet(0);//工作表编号从0开始
			
			int columns = sheet.getColumns();//获得当前工作表中的列数
			int rows = sheet.getRows();//获得当前工作表中的行数
			log.info("列数："+columns+"，行数："+rows);
			
			for(int i = 1; i < rows; i++) {
				//遇到空行，退出循环
				if (sheet.getCell(0,i).getContents() == null || sheet.getCell(0,i).getContents().equals("")) {
					break;
				}
				
				Utilities u = new Utilities();
				
				//读取每行中各单元格的内容，并给u对象赋值
				House house = managementService.findHouseByHouseId(sheet.getCell(0,i).getContents());
				if (house == null) {
					request.setAttribute("houseNotFoundError", "房产编号有误，找不到此编号"+ sheet.getCell(0,i).getContents() +"所对应的的房产信息！");
					return mapping.findForward("upload");
				}
				u.setHouse(house);
				
				//少数房产家中有2个电表或水表
				u.setPowerBegin(Float.parseFloat(sheet.getCell(2,i).getContents()));
				u.setPowerEnd(Float.parseFloat(sheet.getCell(3,i).getContents()));
				u.setPower2Begin(Float.parseFloat(sheet.getCell(4, i).getContents()));
				u.setPower2End(Float.parseFloat(sheet.getCell(5,i).getContents()));
				
				u.setWaterBegin(Float.parseFloat(sheet.getCell(6,i).getContents()));
				u.setWaterEnd(Float.parseFloat(sheet.getCell(7,i).getContents()));
				u.setWater2Begin(Float.parseFloat(sheet.getCell(8, i).getContents()));
				u.setWater2End(Float.parseFloat(sheet.getCell(9,i).getContents()));
				
				u.setYear(chargeYear);
				u.setMonth(chargeMonth);
				
				businessService.saveUtilities(u);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				//操作完毕，关闭对象
				workbook.close();
				fis.close();
			} catch (Exception e) {
			}
		}
		request.setAttribute("readEXCELSuccess", "导入数据成功");
		
		return mapping.findForward("uploadSave");
	}	
}
